package com.android.alarmbuy.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.alarmbuy.AlarmApplication;
import com.android.alarmbuy.utils.SharePreferenceUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Retrofit;

/**
 * Created by Administrator on 2018/9/5.
 */

public class AlarmService extends Service {


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Timer timer = new Timer();
        timer.schedule(timerTask, 0, 1000 * 60 * 5);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
    }

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            getAlarm();
        }
    };

    private void getAlarm() {
        OkGo.<String>get("http://zx.maichaye.cn/get_alarm.php")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String s = response.body().toString();
                        Log.d("leihuiming", "response = " + s);
                        SharePreferenceUtil.saveString(getApplicationContext(), "alarm", s);
                        AlarmApplication.response = s;
                        if(s.equals("1")) {
                            AlarmApplication.playSound();
                            sendBroadcast(new Intent("com.android.alarmbuy"));
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }
}
